package mall

import (
	"context"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzmallbrand"
	"private-domain-overseas-service/tools/ent/hzmallsite"
	"private-domain-overseas-service/tools/ent/predicate"
	"sort"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallBrandListTreeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewMallBrandListTreeLogic - 品牌树形列表
func NewMallBrandListTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallBrandListTreeLogic {
	return &MallBrandListTreeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallBrandListTreeLogic) MallBrandListTree() (resp *types.MallBrandTreeResponse, err error) {
	// 创建实例
	brandDao := mall.NewMallBrandDao(l.ctx, l.svcCtx)
	siteDao := mall.NewMallSiteDao(l.ctx, l.svcCtx)

	// 查询品牌一级信息
	brandConditions := make([]predicate.HzMallBrand, 0)
	brandConditions = append(brandConditions, hzmallbrand.DeleteAtIsNil(),
		hzmallbrand.MallBrandSiteIDEQ(0),
		hzmallbrand.MallBrandParentIDEQ(0))
	brandList, err := brandDao.MallBrandConditionsAll(brandConditions)
	if err != nil {
		return nil, err
	}

	//组装一级品牌数据
	list := lo.Map(brandList, func(item *ent.HzMallBrand, _ int) *types.MallBrandTree {
		//处理品牌图标
		mallBrandIcon := ""
		if item.MallBrandIcon != "" {
			mallBrandIcon = constant.MallGoodsImage + item.MallBrandIcon
		}
		// 查询品牌子目录
		childBrandConditions := make([]predicate.HzMallBrand, 0)
		childBrandConditions = append(childBrandConditions, hzmallbrand.DeleteAtIsNil(),
			hzmallbrand.MallBrandParentIDEQ(int64(item.ID)))
		childBrandList, _ := brandDao.MallBrandConditionsAll(childBrandConditions)
		children := make([]*types.MallBrandTree, 0)

		if len(childBrandList) > 0 {
			children = lo.Map(childBrandList, func(childItem *ent.HzMallBrand, _ int) *types.MallBrandTree {
				//处理品牌图标
				childMallBrandIcon := ""
				if childItem.MallBrandIcon != "" {
					childMallBrandIcon = constant.MallGoodsImage + childItem.MallBrandIcon
				}
				//处理站点名称
				mallBrandSiteName := ""
				if childItem.MallBrandSiteID != 0 {
					brandSiteCondition := make([]predicate.HzMallSite, 0)
					brandSiteCondition = append(brandSiteCondition, hzmallsite.IDEQ(int(childItem.MallBrandSiteID)))
					siteInfo, _ := siteDao.MallSiteConditionsFirst(brandSiteCondition)
					mallBrandSiteName = siteInfo.MallSiteName
				}
				return &types.MallBrandTree{
					Id:                  int64(childItem.ID),
					MallBrandIcon:       childMallBrandIcon,
					MallBrandName:       childItem.MallBrandName,
					MallBrandUrl:        childItem.MallBrandURL,
					MallBrandSort:       childItem.MallBrandSort,
					MallBrandSiteId:     childItem.MallBrandSiteID,
					MallBrandSiteName:   mallBrandSiteName,
					MallBrandSiteStatus: childItem.MallBrandSiteStatus,
					MallBrandSiteShow:   childItem.MallBrandSiteShow,
					MallBrandParentId:   childItem.MallBrandParentID,
					BrandCommissionRate: childItem.BrandCommissionRate,
					CreatedAt:           time.Unix(childItem.CreatedAt, 0).Format(time.DateTime),
					UpdatedAt:           time.Unix(childItem.UpdateAt, 0).Format(time.DateTime),
					Children:            nil,
				}
			})
		}

		return &types.MallBrandTree{
			Id:                  int64(item.ID),
			MallBrandIcon:       mallBrandIcon,
			MallBrandName:       item.MallBrandName,
			MallBrandUrl:        item.MallBrandURL,
			MallBrandSort:       item.MallBrandSort,
			MallBrandSiteId:     item.MallBrandSiteID,
			MallBrandSiteName:   "",
			MallBrandSiteStatus: item.MallBrandSiteStatus,
			MallBrandSiteShow:   item.MallBrandSiteShow,
			MallBrandParentId:   0,
			CreatedAt:           time.Unix(item.CreatedAt, 0).Format(time.DateTime),
			UpdatedAt:           time.Unix(item.UpdateAt, 0).Format(time.DateTime),
			Children:            children,
		}
	})
	resp = &types.MallBrandTreeResponse{
		List: list,
	}
	return resp, nil
	//// 转换为树形结构
	//brandMap := make(map[int64]*types.MallBrandTree)
	//var rootBrand []*types.MallBrandTree
	//
	//// 先转换为MallBrandTree并建立映射
	//for _, brandTree := range brandList {
	//	// 根据站点ID查询站点名称
	//	siteName := ""
	//	if brandTree.MallBrandSiteID != 0 {
	//		siteConditions := make([]predicate.HzMallSite, 0)
	//		siteConditions = append(siteConditions, hzmallsite.DeleteAtIsNil())
	//		siteConditions = append(siteConditions, hzmallsite.IDEQ(int(brandTree.MallBrandSiteID)))
	//		siteInfo, _ := siteDao.MallSiteConditionsFirst(siteConditions)
	//		if siteInfo != nil {
	//			siteName = siteInfo.MallSiteName
	//		}
	//	}
	//
	//	// 组装数据
	//	tree := &types.MallBrandTree{
	//		Id:                  int64(brandTree.ID),
	//		MallBrandIcon:       brandTree.MallBrandIcon,
	//		MallBrandName:       brandTree.MallBrandName,
	//		MallBrandUrl:        brandTree.MallBrandURL,
	//		MallBrandSort:       brandTree.MallBrandSort,
	//		MallBrandSiteId:     brandTree.MallBrandSiteID,
	//		MallBrandSiteName:   siteName,
	//		MallBrandSiteStatus: brandTree.MallBrandSiteStatus,
	//		MallBrandSiteShow:   brandTree.MallBrandSiteShow,
	//		MallBrandParentId:   brandTree.MallBrandParentID,
	//		CreatedAt:           time.Unix(brandTree.CreatedAt, 0).Format(time.DateTime),
	//		UpdatedAt:           time.Unix(brandTree.UpdateAt, 0).Format(time.DateTime),
	//		Children:            make([]*types.MallBrandTree, 0),
	//	}
	//	brandMap[int64(brandTree.ID)] = tree
	//}
	//
	//// 建立父子关系
	//for _, tree := range brandMap {
	//	if tree.MallBrandParentId == 0 {
	//		// 根节点
	//		rootBrand = append(rootBrand, tree)
	//	} else {
	//		// 将当前节点添加到父节点的children中
	//		if parent, exists := brandMap[tree.MallBrandParentId]; exists {
	//			parent.Children = append(parent.Children, tree)
	//		}
	//	}
	//}
	//
	//// 按照sort字段排序每个层级的节点
	//l.handlerSortCategoryTree(rootBrand)
	//
	//// 转换为响应类型
	//resp = &types.MallBrandTreeResponse{
	//	List: make([]*types.MallBrandTree, len(rootBrand)),
	//}
	//
	//// 复制数据
	//for i, item := range rootBrand {
	//	resp.List[i] = l.handlerConvertToTypeCategoryTree(item)
	//}
	//
	//return resp, nil
}

// handlerConvertToTypeCategoryTree - 构建品牌树
func (l *MallBrandListTreeLogic) handlerConvertToTypeCategoryTree(tree *types.MallBrandTree) *types.MallBrandTree {
	if tree == nil {
		return nil
	}

	result := &types.MallBrandTree{
		Id:                  tree.Id,
		MallBrandIcon:       constant.MallGoodsImage + tree.MallBrandIcon,
		MallBrandName:       tree.MallBrandName,
		MallBrandUrl:        tree.MallBrandUrl,
		MallBrandSort:       tree.MallBrandSort,
		MallBrandSiteStatus: tree.MallBrandSiteStatus,
		MallBrandSiteShow:   tree.MallBrandSiteShow,
		MallBrandSiteId:     tree.MallBrandSiteId,
		MallBrandSiteName:   tree.MallBrandSiteName,
		MallBrandParentId:   tree.MallBrandParentId,
		CreatedAt:           tree.CreatedAt,
		UpdatedAt:           tree.UpdatedAt,
		//Children:          nil,
	}

	// 递归转换子节点 只有当子节点存在时才处理
	if len(tree.Children) > 0 {
		result.Children = make([]*types.MallBrandTree, len(tree.Children))
		for i, child := range tree.Children {
			result.Children[i] = l.handlerConvertToTypeCategoryTree(child)
		}
	}

	return result
}

// handlerSortCategoryTree - 递归排序分类树
func (l *MallBrandListTreeLogic) handlerSortCategoryTree(brand []*types.MallBrandTree) {
	// 排序当前层级
	sort.Slice(brand, func(i, j int) bool {
		return brand[i].MallBrandSort < brand[j].MallBrandSort
	})

	// 递归排序子节点
	for _, category := range brand {
		if len(category.Children) > 0 {
			l.handlerSortCategoryTree(category.Children)
		}
	}
}
